package main

import (
	"encoding/json"
	"fmt"
	"net"
	"strconv"
	"time"

	"gitcode.com/shexk/xframe/Plugins/mq/core"
	x "gitcode.com/shexk/xframe/plugin"
)

type Server struct {
	obj    *x.AppObj
	server *core.TcpServer
	//DataBus chan x.PluginMsg
}

func LoadPlugin() x.Plugin {
	return &Server{}
}

func GetNanoID() uint64 {
	return uint64(time.Now().UnixNano()) //time.Now().UnixMilli()
}

type DBRequest struct {
	Name  string
	Value string
}

func (p *Server) Init(obj *x.AppObj) error {
	p.obj = obj
	fmt.Println("MQ Init")
	core.GetDBCmd().SetDB(obj.DB)

	buf, err := json.Marshal(DBRequest{Name: "ReadKeyValue", Value: "TcpServerPort"})
	if err != nil {
		return err
	}
	p.PostPluginMsg(string(buf), []byte{})

	return nil
}

func (p *Server) Start() error {
	// 实现具体逻辑
	fmt.Println("MQ Start")
	ss := p.ReadKeyValue("MQ.Port")
	port := StringToUint64(string(ss))

	p.server = core.NewTcpServer(port)

	p.server.OnServerEvent = func(conn net.Conn, state int, err error, data []byte, datasize uint32) {
		core.GetBroker().ProcessData(conn, state, err, data, datasize)
	}

	if err := p.server.Start(); err != nil {
		println("Error starting server:", err.Error())
		return err
	}

	core.GetTopicMng().LoadAllTopicsInfoFromDB()
	core.GetBroker().StartProcessTask()
	return nil
}
func (p *Server) Stop() error {
	// 实现具体逻辑
	fmt.Println("MQ Stop")
	return nil
}

func StringToUint64(s string) uint64 {
	// 尝试解析为十进制uint64
	num, err := strconv.ParseUint(s, 10, 64)
	if err != nil {
		return 0
	}
	return num
}

type SocketInfo struct {
	ClientAddr  string
	ClientState string
}

func (p *Server) Receiver(dt *x.PluginMsg) {
	fmt.Println("MQ Receiver:", dt)

}

const (
	Plugin_Name = "MQ"
	Topic_Name  = "TCP.Server.Topic"
)

func (p *Server) Meta() *x.PluginMeta {
	return x.NewPluginMeta(Plugin_Name, "1.0.0", "Shexk")
}
func (p *Server) WriteLog(log string) {
	obj := x.Object{Type: x.Type_Service, Name: "CommandCenter"}
	msg := x.PluginMsg{ID: x.GetMessageID(), Cmd: x.Command_Log, Sender: x.Object{Type: x.Type_Plugin, Name: p.Meta().Name},
		Receiver: []x.Object{obj},
		Option:   "", Data: []byte(log)}
	p.obj.DataBus <- &msg
}

func (p *Server) PostPluginMsg(option string, data []byte) {
	obj := x.Object{Type: x.Type_Service, Name: "CommandCenter"}
	msg := x.PluginMsg{ID: x.GetMessageID(), Cmd: x.Command_DB, Sender: x.Object{Type: x.Type_Plugin, Name: p.Meta().Name},
		Receiver: []x.Object{obj},
		Option:   option, Data: data}
	p.obj.DataBus <- &msg
}
func (p *Server) ReadKeyValue(name string) string {
	if p.obj.DB == nil {
		return ""
	}

	rows, err := p.obj.DB.Query("Select value from KeyValue where Key='" + name + "'")
	if err != nil {
		fmt.Println("Read Record Error:" + err.Error())
		return ""
	}
	defer rows.Close()
	if rows.Next() {
		aes := ""
		if err = rows.Scan(&aes); err != nil {
			fmt.Println("Read Record Value Error:" + err.Error())
			return ""
		}
		return aes
	}
	return ""
}

//go build -buildmode=plugin -o mq.so  .
